﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Net.Sockets;

namespace WuHouCiClient
{
    public class CNet
    {
        private const int BufferSize = 2048;
        private static CNet tcpClient = null;

        //单列模式
        public static CNet getInstance()
        {
            if (tcpClient == null)
            {
                tcpClient = new CNet();
                return tcpClient;
            }
            else
                return tcpClient;
        }

        //Net能力一：建立连接
        public static TcpClient createConnect(string ip = "127.0.0.1", int port = 8080)
        {
            //
            //byte[] ipBytes = Encoding.UTF8.GetBytes(i);
            //IPAddress ip = new IPAddress(ipBytes); 
            
            //
            TcpClient client = new TcpClient();
            try
            {
               // if (linkCallback == null)
                    client.Connect(ip, port);
                //else
                 //   client.BeginConnect(ip,port,);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
            return client;
        }
        //能力二：收发包能力
        public static void sendPakage(byte[] message,TcpClient tcpClient)
        {
            NetworkStream streamToServer = tcpClient.GetStream();
            streamToServer.Write(message,0,message.Length);
        }
        // 收包
        public static byte[] recvPackage(ref int readNum, TcpClient tcpClient)
        {
            NetworkStream streamToClient = tcpClient.GetStream();
            if (streamToClient.CanRead == true)
            {
                byte[] message = new byte[BufferSize];
                readNum = streamToClient.Read(message, 0, message.Length);
                return message;
            }
            else
            {
                start_link link_instance = start_link.getInstance();
                link_instance.setLink();
                return new byte[0];
            }
           
        }
        //断开连接
        public static bool disconnect(TcpClient tcpClient)
        {
            tcpClient.Close();
            return true;
        }

        //////////////////////////////////
        ////////////////上面部分是工具函数
        private List<SuperLogic> function_list;

        public void init() { function_list = new List<SuperLogic>();}

        //向管理器内注册,每一帧调用时会根据 id通知相应的类
        public bool register_client(SuperLogic sl)
        {
            this.function_list.Add(sl);
            return true;
        }

        public void recvPulicFunction(Userdata dat)
        {
            foreach (SuperLogic sl in this.function_list)
            {
                if (sl.getId == dat.id)
                {
                    sl.deserialize(dat.dataInfo);
                }
            }
        }
        
    //this is class {
    }
}
